<a class="dropdown-item text-dark" asp-area="Admin" asp-controller="Product" asp-action="Index">產品</a>
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Size { get; set; }
[Required]
[Range(1, 10000)]
public double Price { get; set; }
public string Description { get; set; }
public string? ImageUrl { get; set; }
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public Category? Category { get; set; }
}
public class ProductVM
{
public Product Product { get; set; }
[ValidateNever]
public IEnumerable<SelectListItem> CategoryList { get; set; }
}
開啟Customer&Admin的/View/_ViewImports.cshtml@using ClothesShop.Models.ViewModels
Product的Model定義了CategoryId,資料表一併新增類別Id做關聯;
1.Product預設資料,增加關聯的CategoryId。
2.CategoryId值要一併填入(不得為空)。
開啟套鍵管理器主控台=>切換預設專案DataAccess。
指令:
1.add-migration addForeignKeyAndUrlForProduct
2.update-database
public DbSet<Product> Products { get; set; }
modelBuilder.Entity<Product>().HasData(
new Product { Id = 1, Name = "圓領質感壓紋短袖上衣", Size = "S", Description = "好搭程度超乎你的想像~~", Price = 330, ImageUrl = "", CategoryId = 1 },
new Product { Id = 2, Name = "蝴蝶結傘擺背心短洋裝", Size = "M", Description = "削肩+滾邊讓洋裝變得不簡單~~", Price = 380, ImageUrl = "", CategoryId = 2 },
new Product { Id = 3, Name = "內搭簡單素踢就能輕鬆出門", Size = "L", Description = "好搭程度超乎你的想像~~", Price = 340, ImageUrl = "", CategoryId = 3 }
);
複製Category與ICategory的Repository,更名為Product/ IProduct ,
選取Category=>Ctrl+Shift+F 用 Product取代。
public class ProductRepository : Repository<Product>, IProductRepository
{
private ApplicationDbContext _db;
public ProductRepository(ApplicationDbContext db) : base(db)
{
_db = db;
}
public void Update(Product obj)
{
var objFromDb = _db.Products.FirstOrDefault(u => u.Id == obj.Id);
if (objFromDb != null)
{
objFromDb.Name = obj.Name;
objFromDb.Size = obj.Size;
objFromDb.Price = obj.Price;
objFromDb.Description = obj.Description;
objFromDb.CategoryId = obj.CategoryId;
if (objFromDb.ImageUrl != null)
{
objFromDb.ImageUrl = obj.ImageUrl;
}
}
}
}
public interface IProductRepository : IRepository<Product>
{
void Update(Product obj);
}